package pack1;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import swim.entitybeans.RegisteredUser;
import swim.sessionbeans.SearchRemote;
import swim.sessionbeans.UserManagerRemote;

/**
 * Servlet implementation class EditInfoServlet
 */
public class EditInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public String firstname;
	public String lastname;
	public String username;
	public String md5oldpassword;
	public String md5newpassword;
	public String mail;
	public String picturename;
	public String pictureest;
	public String pictureurl;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Edit Info Personali");
		try {
			InitialContext jndiContext = new InitialContext();
			UserManagerRemote userman = (UserManagerRemote) jndiContext.lookup("UserManager/remote");
			SearchRemote search = (SearchRemote) jndiContext.lookup("Search/remote");
			RegisteredUser loggeduser = (RegisteredUser)request.getSession().getAttribute("loggeduser");						
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> fields = upload.parseRequest(request);			
			Iterator<FileItem> it = fields.iterator();
			if (!it.hasNext()) {
				return;
			}
			while (it.hasNext()) {				
				FileItem fileItem = it.next();
				boolean isFormField = fileItem.isFormField();
				if (!isFormField) {
					if (md5oldpassword.equals(loggeduser.getPassword()) && !fileItem.getName().equals("")) {
						try{
						System.out.println("NON SONO UN FORM FIELD");
							picturename = fileItem.getName();
							System.out.println(picturename);
							pictureest = picturename.substring(picturename.lastIndexOf("."));					
							picturename = loggeduser.getUsername()+"_picture_"+Long.toString(System.currentTimeMillis())+pictureest;									
							String root = getServletContext().getRealPath("/");
						
							File path = new File(root + "/users_pictures");
							if(!path.exists()){
								path.mkdirs();
							}
						
							File uploadedFile = new File(path + "/" + picturename);
						
							fileItem.write(uploadedFile);						
							pictureurl = "./users_pictures/"+picturename;
						}catch (Exception e){
							e.printStackTrace();
							pictureurl = "./users_pictures/default.png";
						}											  
						System.out.println("IMMAGINE SALVATA: "+pictureurl);
					}else{
						pictureurl = null;
					}									
				}else{							
					//System.out.println("SONO UN FORM FIELD");
					String fieldName = fileItem.getFieldName();					
						if(fieldName.equals("firstname")){ 
							firstname = fileItem.getString();
						}else if(fieldName.equals("lastname")){
							lastname = fileItem.getString();							
						}else if(fieldName.equals("oldpassword")){
							String password = fileItem.getString();
							MessageDigest md = MessageDigest.getInstance("MD5"); //START MD5 conversion
							md.update(password.getBytes(),0,password.length());  //..
							md5oldpassword = new BigInteger(1,md.digest()).toString(16); // password in md5 in md5password
						}else if(fieldName.equals("newpassword")){
							String password = fileItem.getString();
							MessageDigest md = MessageDigest.getInstance("MD5"); //START MD5 conversion
							md.update(password.getBytes(),0,password.length());  //..
							md5newpassword = new BigInteger(1,md.digest()).toString(16); // password in md5 in md5password
						}else if(fieldName.equals("mail")){
							mail = fileItem.getString();							
						}
				}
			}
			if (md5oldpassword.equals(loggeduser.getPassword())) {
				userman.editPersonalInfo(loggeduser.getId(), null, md5newpassword, 	mail, firstname, lastname, pictureurl);		
				request.getSession().setAttribute("pageMessage", "Personal Info modified correctly.");
				request.getSession().setAttribute("pageMessageType", "success");
				loggeduser = search.searchById(loggeduser.getId());
				request.getSession().setAttribute("loggeduser", loggeduser);
				response.sendRedirect("personalpage.jsp");
			}else{
				request.getSession().setAttribute("pageMessage", "Incorrect Current Password");
				request.getSession().setAttribute("pageMessageType", "error");
				response.sendRedirect("personalpage.jsp");
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
